<template>
  <div class="venue-edit-container">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑场馆' : '新增场馆' }}</h2>
      <el-button @click="goBack">返回列表</el-button>
    </div>
    
    <el-card shadow="never">
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        v-loading="loading"
      >
        <el-form-item label="场馆名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入场馆名称" />
        </el-form-item>
        
        <el-form-item label="场馆类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择场馆类型" style="width: 100%">
            <el-option v-for="item in venueTypes" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" @change="searchAddress" />
          <el-button type="primary" style="margin-top: 10px;" @click="searchAddress">定位地址</el-button>
        </el-form-item>
        
        <el-form-item label="所在区域" prop="location">
          <el-input v-model="form.location" placeholder="请输入所在区域" />
        </el-form-item>
        
        <!-- 地图容器 -->
        <el-form-item label="地图位置">
          <div id="map-container" style="height: 400px; width: 100%;"></div>
          <div style="margin-top: 10px;">
            <span>经度: {{ form.longitude }}</span>
            <span style="margin-left: 20px;">纬度: {{ form.latitude }}</span>
          </div>
        </el-form-item>
        
        <el-form-item label="场馆介绍" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入场馆介绍" />
        </el-form-item>
        
        <el-form-item label="开放时间" prop="open_time">
          <el-time-picker
            v-model="openTimeRange"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 100%"
            @change="handleTimeChange"
          />
        </el-form-item>
        
        <el-form-item label="场馆状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="场馆图片" prop="images">
          <el-upload
            class="venue-image-uploader"
            :action="getUploadUrl()"
            list-type="picture-card"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :headers="uploadHeaders"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="getFullImageUrl(dialogImageUrl)" alt="预览图片" />
          </el-dialog>
        </el-form-item>
        
        <!-- 时间段设置 -->
        <el-divider content-position="left">时间段设置</el-divider>
        
        <div v-for="(timeSlot, index) in form.time_slots" :key="index" class="time-slot-item">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item :label="`时间段${index + 1}`" :prop="`time_slots.${index}.time_range`">
                <el-time-picker
                  v-model="timeSlot.time_range"
                  is-range
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  format="HH:mm"
                  value-format="HH:mm"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="价格" :prop="`time_slots.${index}.price`">
                <el-input-number v-model="timeSlot.price" :min="0" :precision="2" :step="10" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="容量" :prop="`time_slots.${index}.capacity`">
                <el-input-number v-model="timeSlot.capacity" :min="1" :step="1" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="4" class="flex-center">
              <el-button type="danger" icon="Delete" circle @click="removeTimeSlot(index)" />
            </el-col>
          </el-row>
        </div>
        
        <el-form-item>
          <el-button type="primary" plain icon="Plus" @click="addTimeSlot">添加时间段</el-button>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { Plus } from '@element-plus/icons-vue'

export default {
  name: 'VenueEdit',
  components: {
    Plus
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const formRef = ref(null)
    const loading = ref(false)
    const submitting = ref(false)
    
    // 动态获取基础API URL，避免硬编码
    const getBaseApiUrl = () => {
      // 在开发环境下，使用vue.config.js中配置的代理目标
      if (process.env.NODE_ENV === 'development') {
        return 'https://dpcurdgwzmkg.sealosbja.site'
      }
      // 生产环境下使用环境变量或默认值
      return process.env.VUE_APP_BASE_URL || window.location.origin
    }

    const baseApiUrl = getBaseApiUrl()
    
    // 百度地图相关
    let map = null
    let marker = null
    let geolocation = null
    
    // 判断是否为编辑模式
    const isEdit = computed(() => {
      return !!route.params.id
    })
    
    // 场馆类型选项
    const venueTypes = [
      { label: '篮球场', value: 'basketball' },
      { label: '足球场', value: 'football' },
      { label: '网球场', value: 'tennis' },
      { label: '羽毛球馆', value: 'badminton' },
      { label: '游泳馆', value: 'swimming' },
      { label: '乒乓球室', value: 'pingpong' }
    ]
    
    // 表单数据
    const form = reactive({
      name: '',
      type: 'basketball', // 设置默认类型为篮球场
      address: '',
      location: '',
      latitude: null,
      longitude: null,
      description: '',
      open_time: '',
      status: 1,
      images: [],
      time_slots: []
    })
    
    // 开放时间范围
    const openTimeRange = ref([])
    
    // 图片上传相关
    const fileList = ref([])
    const dialogImageUrl = ref('')
    const dialogVisible = ref(false)
    
    // 上传请求头
    const uploadHeaders = computed(() => {
      return {
        Authorization: `Bearer ${localStorage.getItem('admin_token')}`
      }
    })
    
    // 获取上传URL
    const getUploadUrl = () => {
        return `${baseApiUrl}/api/v1/admin/upload`
    }

    // 获取完整的图片URL
    const getFullImageUrl = (url) => {
      if (!url) return '';
      
      const correctBaseUrl = baseApiUrl;
      const wrongBaseUrl = 'https://hm.yunxitech.cn';

      let finalUrl = url;

      // 如果URL中包含错误的域名，强制替换成正确的域名
      if (finalUrl.startsWith(wrongBaseUrl)) {
        finalUrl = finalUrl.replace(wrongBaseUrl, correctBaseUrl);
        return finalUrl;
      }
      
      // 如果已经是正确的完整http/https链接，则直接返回
      if (finalUrl.startsWith('http')) {
        return finalUrl;
      }
      
      // 如果路径以'/'开头，则直接拼接域名
      if (finalUrl.startsWith('/')) {
        return `${correctBaseUrl}${finalUrl}`;
      }
      
      // 默认拼接基础URL和存储路径
      return `${correctBaseUrl}/uploads/venue/${finalUrl}`;
    }
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入场馆名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择场馆类型', trigger: 'change' }
      ],
      address: [
        { required: true, message: '请输入详细地址', trigger: 'blur' }
      ],
      location: [
        { required: true, message: '请输入所在区域', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入场馆介绍', trigger: 'blur' }
      ],
      open_time: [
        { required: true, message: '请设置开放时间', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择场馆状态', trigger: 'change' }
      ]
    }
    
    // 初始化百度地图
    const initMap = () => {
      // 动态加载百度地图API
      const script = document.createElement('script')
      script.type = 'text/javascript'
      script.src = 'https://api.map.baidu.com/api?v=3.0&ak=Hi4Ddf8yBSFLZUUgxJW1awYf4lAuz0hK&callback=initBaiduMap'
      document.head.appendChild(script)
      
      // 全局回调函数
      window.initBaiduMap = () => {
        // 创建地图实例
        map = new window.BMap.Map('map-container')
        // 设置中心点和缩放级别
        const point = new window.BMap.Point(116.404, 39.915) // 默认北京
        map.centerAndZoom(point, 15)
        // 启用滚轮缩放
        map.enableScrollWheelZoom(true)
        // 添加控件
        map.addControl(new window.BMap.NavigationControl())
        map.addControl(new window.BMap.ScaleControl())
        
        // 创建标记点
        marker = new window.BMap.Marker(point)
        map.addOverlay(marker)
        
        // 点击地图设置标记点和经纬度
        map.addEventListener('click', (e) => {
          map.clearOverlays()
          const newPoint = new window.BMap.Point(e.point.lng, e.point.lat)
          marker = new window.BMap.Marker(newPoint)
          map.addOverlay(marker)
          
          // 更新表单经纬度
          form.longitude = e.point.lng
          form.latitude = e.point.lat
          
          // 反向地理编码获取地址
          const geoc = new window.BMap.Geocoder()
          geoc.getLocation(newPoint, (rs) => {
            const addComp = rs.addressComponents
            form.address = `${addComp.province}${addComp.city}${addComp.district}${addComp.street}${addComp.streetNumber}`
            form.location = addComp.district
          })
        })
        
        // 如果有经纬度，定位到该位置
        if (form.latitude && form.longitude) {
          const venuePoint = new window.BMap.Point(form.longitude, form.latitude)
          map.centerAndZoom(venuePoint, 15)
          marker = new window.BMap.Marker(venuePoint)
          map.addOverlay(marker)
        } else {
          // 尝试获取当前位置
          geolocation = new window.BMap.Geolocation()
          geolocation.getCurrentPosition((r) => {
            if (geolocation.getStatus() === window.BMAP_STATUS_SUCCESS) {
              map.panTo(r.point)
            }
          })
        }
      }
    }
    
    // 根据地址搜索位置
    const searchAddress = () => {
      if (!form.address || !map) return
      
      const localSearch = new window.BMap.LocalSearch(map, {
        renderOptions: { map: map, autoViewport: true }
      })
      
      localSearch.setSearchCompleteCallback((results) => {
        if (results && results.getPoi(0)) {
          const poi = results.getPoi(0)
          map.centerAndZoom(poi.point, 15)
          map.clearOverlays()
          marker = new window.BMap.Marker(poi.point)
          map.addOverlay(marker)
          
          // 更新经纬度
          form.longitude = poi.point.lng
          form.latitude = poi.point.lat
          
          // 获取区域
          const geoc = new window.BMap.Geocoder()
          geoc.getLocation(poi.point, (rs) => {
            const addComp = rs.addressComponents
            form.location = addComp.district
          })
        } else {
          ElMessage.warning('未找到该地址，请尝试更详细的地址')
        }
      })
      
      localSearch.search(form.address)
    }
    
    // 处理时间变更
    const handleTimeChange = (val) => {
      if (val && val.length === 2) {
        form.open_time = `${val[0]}-${val[1]}`
      } else {
        form.open_time = ''
      }
    }
    
    // 添加时间段
    const addTimeSlot = () => {
      form.time_slots.push({
        time_range: [],
        price: 0,
        capacity: 1
      })
    }
    
    // 移除时间段
    const removeTimeSlot = (index) => {
      form.time_slots.splice(index, 1)
    }
    
    // 图片预览
    const handlePictureCardPreview = (file) => {
      dialogImageUrl.value = file.url
      dialogVisible.value = true
    }
    
    // 图片移除
    const handleRemove = (file) => {
      const index = fileList.value.findIndex(item => item.uid === file.uid)
      if (index !== -1) {
        fileList.value.splice(index, 1)
        form.images = form.images.filter(img => img !== file.url)
      }
    }
    
    // 从完整URL中提取相对路径
    const extractRelativePath = (url) => {
      if (!url) return ''
      
      // 如果是相对路径，直接返回
      if (!url.startsWith('http')) {
        return url
      }
      
      // 从完整URL中提取相对路径
      const urlObj = new URL(url)
      return urlObj.pathname
    }

    // 图片上传成功
    const handleUploadSuccess = (response, file) => {
      // 后端返回的是相对路径，如 /uploads/venue/xxx.jpg
      const relativePath = response.data.url
      
      // 构建完整的图片URL用于显示
      const fullUrl = getFullImageUrl(relativePath)
      
      // 添加到文件列表（显示用完整URL）
      fileList.value.push({
        name: file.name,
        url: fullUrl
      })
      
      // 添加到表单数据（保存用相对路径）
      form.images.push(relativePath)
    }
    
    // 获取场馆详情
    const fetchVenue = async () => {
      console.log('🔍 开始获取场馆详情，场馆ID:', route.params.id)
      loading.value = true
      try {
        const response = await request.get(`/v1/admin/venues/${route.params.id}`)
        const venueData = response.data
        
        // 调试：打印后端返回的原始数据
        console.log('🏟️ 后端返回的原始场馆数据:', venueData)
        console.log('📸 原始图片数据:', venueData.images)
        
        Object.assign(form, venueData)

        // 关键修复：在这里处理图片URL
        if (venueData.images && Array.isArray(venueData.images)) {
          console.log('处理前的图片URLs:', venueData.images)
          
          fileList.value = venueData.images.map(img => {
            const correctedUrl = getFullImageUrl(img)
            console.log(`原始URL: ${img} -> 修正后URL: ${correctedUrl}`)
            return {
              name: img.split('/').pop(),
              url: correctedUrl,
              rawUrl: img
            }
          })
          
          console.log('最终的fileList:', fileList.value)
          form.images = venueData.images
        }

        // 处理开放时间
        if (form.open_time) {
          openTimeRange.value = form.open_time.split('-')
        }
        
        // 更新地图
        if (form.latitude && form.longitude) {
          const point = new window.BMap.Point(form.longitude, form.latitude)
          map.centerAndZoom(point, 15)
          if (marker) {
            marker.setPosition(point)
          } else {
            marker = new window.BMap.Marker(point)
            map.addOverlay(marker)
          }
        }
      } catch (error) {
        ElMessage.error('获取场馆详情失败')
        console.error(error)
      } finally {
        loading.value = false
      }
    }
    
    // 提交表单
    const submitForm = () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            // 处理时间段数据
            const processedTimeSlots = form.time_slots.map(slot => {
              return {
                start_time: slot.time_range[0],
                end_time: slot.time_range[1],
                price: slot.price,
                capacity: slot.capacity
              }
            })
            
            // 确保图片数据为相对路径
            const cleanImages = form.images.map(img => extractRelativePath(img))
            
            const submitData = {
              ...form,
              images: cleanImages,
              time_slots: processedTimeSlots
            }
            
            if (isEdit.value) {
              // 更新场馆
              await request.put(`/v1/admin/venues/${route.params.id}`, submitData)
              ElMessage.success('更新场馆成功')
            } else {
              // 创建场馆
              await request.post('/v1/admin/venues', submitData)
              ElMessage.success('创建场馆成功')
            }
            
            // 返回列表页
            router.push('/venue/list')
          } catch (error) {
            console.error('保存场馆失败', error)
            ElMessage.error('保存场馆失败')
          } finally {
            submitting.value = false
          }
        }
      })
    }
    
    // 返回列表页
    const goBack = () => {
      router.push('/venue/list')
    }
    
    // 初始化
    onMounted(() => {
      fetchVenue()
      
      // 初始化地图
      initMap()
      
      // 如果是新增，默认添加一个时间段
      if (!isEdit.value && form.time_slots.length === 0) {
        addTimeSlot()
      }
    })
    
    // 组件销毁前清理
    onBeforeUnmount(() => {
      // 清理百度地图全局回调
      if (window.initBaiduMap) {
        window.initBaiduMap = null
      }
    })
    
    return {
      formRef,
      form,
      rules,
      loading,
      submitting,
      isEdit,
      venueTypes,
      openTimeRange,
      fileList,
      dialogImageUrl,
      dialogVisible,
      uploadHeaders,
      handleTimeChange,
      addTimeSlot,
      removeTimeSlot,
      handlePictureCardPreview,
      handleRemove,
      handleUploadSuccess,
      searchAddress,
      submitForm,
      goBack,
      getUploadUrl,
      getFullImageUrl,
      extractRelativePath
    }
  }
}
</script>

<style lang="scss" scoped>
.venue-edit-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 20px;
    }
  }
  
  .time-slot-item {
    padding: 15px;
    margin-bottom: 15px;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
  }
  
  .flex-center {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style> 